

package cn.shengchao.examstar.me.address.acl.adapters.repositories;

import cn.shengchao.examstar.me.address.acl.ports.repositories.IAddressRepository;
import cn.shengchao.examstar.me.address.domain.Address;
import cn.shengchao.examstar.me.infrastructure.dao.AddressDao;
import cn.shengchao.examstar.me.infrastructure.dao.po.TAddress;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class AddressRepository implements IAddressRepository {

    @Autowired
    private AddressDao addressDao;

    @Override
    public Address save(Address address) {
        TAddress tAddress = new TAddress();
        tAddress.setProvince(address.getProvince());
        tAddress.setCity(address.getCity());
        tAddress.setCounty(address.getCounty());
        tAddress.setDetail(address.getDetail());
        tAddress.setUserId(address.getUserId());
        tAddress.setDefaultAddress(address.getDefaultAddress());
        tAddress.setId(address.getId());
        addressDao.insertOrUpdate(tAddress);
        address.setId(tAddress.getId());
        return address;
    }

    @Override
    public List<Address> getList(Long userId) {
        List<TAddress> list = addressDao.selectList(new LambdaQueryWrapper<TAddress>().eq(TAddress::getUserId, userId));
        return list.stream().map(this::of).toList();
    }

    private Address of(TAddress tAddress) {
        Address address = new Address();
        address.setId(tAddress.getId());
        address.setProvince(tAddress.getProvince());
        address.setCity(tAddress.getCity());
        address.setCounty(tAddress.getCounty());
        address.setDetail(tAddress.getDetail());
        address.setDefaultAddress(tAddress.getDefaultAddress());
        address.setUserId(tAddress.getUserId());
        address.setDefaultAddress(tAddress.getDefaultAddress());
        return address;
    }

    @Override
    public void updateDefaultAddress(Address address, boolean isDefault) {
        TAddress tAddress = new TAddress();
        tAddress.setDefaultAddress(isDefault);
        addressDao.update(tAddress, new LambdaQueryWrapper<TAddress>().eq(TAddress::getId, address.getId()));
    }
}
